package tree.traverse;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 中序遍历二叉树
 *
 * @author xushijian
 * @date 2021/08/02 17:09
 */
public class InOrder {

    public static void main(String[] args) {
        //1,2,3,null,null,4,5
        TreeNode treeNode = new TreeNode(1);
        treeNode.left = new TreeNode(2);
        treeNode.right = new TreeNode(3);
        treeNode.right.left = new TreeNode(4);
        treeNode.right.right = new TreeNode(5);

        InOrder bt = new InOrder();
        // 2 4 5 3 1               //2 1 4 3 5
        System.out.println("中序遍历： " + bt.inOrder(treeNode));
    }

    /**
     * 中序遍历二叉树（ 根中，从左到右）
     *
     * @param root 树
     * @return 值
     */
    public List<Integer> inOrder(TreeNode root) {

        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode current = root;
        while (current != null || !stack.isEmpty()) {
            //取所有左节点
            while (current != null) {
                stack.push(current);
                current = current.left;
            }
            current = stack.pop();
            result.add(current.val);
            current = current.right;
        }

        return result;
    }
}